package com.hyg.lib_music.ui.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.Music.MusicCateData;
import com.hyg.lib_music.R;
import com.hyg.lib_music.adapter.MusicCateFooterViewBinder;
import com.hyg.lib_music.adapter.MusicCateHeadViewBinder;
import com.hyg.lib_music.adapter.MusicCateViewBinder;
import com.hyg.lib_music.presenter.MusicCateListContract;
import com.hyg.lib_music.presenter.di.components.DaggerActivityComponent;
import com.hyg.lib_music.service.MusicService;
import com.hyg.lib_music.ui.activity.MainMusicBedActivity;
import com.hyg.lib_music.util.ApplicationComponentUtil;

import java.util.List;

import javax.inject.Inject;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

import static me.drakeet.multitype.MultiTypeAsserts.assertAllRegistered;
import static me.drakeet.multitype.MultiTypeAsserts.assertHasTheSameAdapter;

public class MusicCateListFragment extends BaseFragment  implements MusicCateListContract.View {

    public static Context mContext;
    private MusicCateData mCate;
    private MusicCateData mSubCate;

    private List<MusicCateData> musicCateDataList;

    @Inject
    MusicCateListContract.Presenter presenter;

    private MultiTypeAdapter mAdapter;

    private Items items;

    private MusicService.MusicServiceBinder serviceBinder;

    public static MusicCateListFragment newInstance(MusicCateData data) {
        MusicCateListFragment fragment = new MusicCateListFragment();
        Bundle args = new Bundle();
        args.putSerializable("cate" , data);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_music_system, container, false);

        RecyclerView mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setBackgroundColor(getResources().getColor(R.color.musicTabBg));
        //Dagger注入

        DaggerActivityComponent.builder()
                .applicationComponent(new ApplicationComponentUtil(BaseApplication.getInstance()).getComponent())
                .build()
                .inject(this);
        if (getArguments() != null) {
            mCate = (MusicCateData)getArguments().getSerializable("cate");
        }
        presenter.setContractView(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        MusicCateHeadViewBinder musicCateHeadViewBinder = new MusicCateHeadViewBinder();

        musicCateHeadViewBinder.setOnMusicCateClickListener(new MusicCateHeadViewBinder.OnMusicCateClickListener() {
            @Override
            public void onItemClick(View view, MusicCateData musicCateData) {
                if(mCate == null && musicCateData.subList!=null &&musicCateData.subList.size()>0){
                    //过滤掉首页有子分类的一级1

                    musicCateData.isExpand = !musicCateData.isExpand;
                    refresh();
                    return;
                }
                mSubCate = musicCateData;
                presenter.existSubCateList(mSubCate.id);

            }

        });
        MusicCateViewBinder musicCateViewBinder = new MusicCateViewBinder();
        musicCateViewBinder.setOnMusicCateClickListener(new MusicCateViewBinder.OnMusicCateClickListener() {
            @Override
            public void onItemClick(View view, MusicCateData musicCateData) {

                mSubCate = musicCateData;
//                presenter.existSubCateList(mSubCate.id);
                enterSubCate(null);
            }

        });
        MusicCateFooterViewBinder musicCateFooterViewBinder = new MusicCateFooterViewBinder();
        musicCateFooterViewBinder.setOnMusicCateFooterClickListener(new MusicCateFooterViewBinder.OnMusicCateFooterClickListener() {
            @Override
            public void onItemClick(View view, MusicCateData musicCateData) {

                mSubCate = musicCateData;
//                presenter.existSubCateList(mSubCate.id);
                enterSubCate(null);
            }

        });

        mAdapter = new MultiTypeAdapter();
        mAdapter.register(MusicCateData.class).to(
                musicCateHeadViewBinder,
                musicCateViewBinder,
                musicCateFooterViewBinder
        ).withClassLinker((position, data) -> {
            int cateId = data.id;

            if (mCate != null) {
                //三级
                if (mCate.id == cateId) {
                    //是头
                    return MusicCateHeadViewBinder.class;
                }

            } else {

                for (int i = 0; i < this.musicCateDataList.size(); i++) {
                    MusicCateData item = this.musicCateDataList.get(i);
                    if (cateId == item.id) {
                        //第一级全是头
                        return MusicCateHeadViewBinder.class;
                    }

                    for (int j = 0; j < item.subList.size(); j++) {
                        MusicCateData sub = item.subList.get(j);
                        if (j == item.subList.size() - 1) {
                            if (cateId == sub.id) {
                                return MusicCateFooterViewBinder.class;
                            }
                        }
                        ;
                    }
                }
            }
            return MusicCateViewBinder.class;

        });

        mRecyclerView.setAdapter(mAdapter);
        assertHasTheSameAdapter(mRecyclerView, mAdapter);

        //绑定播放服务
        Intent i = new Intent(getActivity(), MusicService.class);
        getActivity().bindService(i, mServiceConnection, getActivity().BIND_AUTO_CREATE);

        if (mCate !=null){
            presenter.getCateList(mCate.id);
        }else{
            presenter.getCateList(0);
        }

        mContext = this.getActivity();
        return view;
    }

    @Override
    public void setCateListData(List<MusicCateData> musicCateDataList) {
        this.musicCateDataList = musicCateDataList;
        refresh();
    }

    @Override
    public void enterSubCate(List<MusicCateData> subList) {

        mSubCate.subList = subList;
        Intent intent = new Intent(mContext, MainMusicBedActivity.class);
        Bundle args = new Bundle();
        args.putSerializable("cate" , mSubCate);
        intent.putExtras(args);
        startActivity(intent);

    }

    private void refresh() {
        items = new Items();

        if (mCate != null){
            //三级
            items.add(mCate);
            for (int i = 0; i < this.musicCateDataList.size(); i++) {

                MusicCateData item = this.musicCateDataList.get(i);
                items.add(item);

            }
        } else {
            if (this.musicCateDataList == null){
                return;
            }
            for (int i = 0; i < this.musicCateDataList.size(); i++) {

                MusicCateData item = this.musicCateDataList.get(i);
                items.add(item);
                if (item.isExpand == true) {
                    for (int j = 0; j < item.subList.size(); j++) {

                        MusicCateData sub = item.subList.get(j);
                        items.add(sub);

                    }
                }
            }
        }
        mAdapter.setItems(items);
        mAdapter.notifyDataSetChanged();
        assertAllRegistered(mAdapter, items);
    }

    //定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mContext.unbindService(mServiceConnection);
    }
}